//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System;
using System.ComponentModel;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using CommunityServer.Components;


namespace CommunityServer.Controls
{
	public class GroupSubscribeLinkButton : HtmlAnchor
	{

		#region Public Properties

		private Group group;
		public virtual Group Group
		{
			get { return group; }
			set { group = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when tracking." ),
		DefaultValue( "" ),
		]
		public virtual string TrackingResourceName 
		{
			get 
			{
				Object state = ViewState["TrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["TrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when not tracking." ),
		DefaultValue( "" ),
		]
		public virtual string NotTrackingResourceName 
		{
			get 
			{
				Object state = ViewState["NotTrackingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["NotTrackingResourceName"] = value; }
		}

		[
		Bindable(true),
		Category( "Appearance" ),
		Description( "Gets or sets the name of the resource to display when the button is working." ),
		DefaultValue( "" ),
		]
		public virtual string WorkingResourceName 
		{
			get 
			{
				Object state = ViewState["WorkingResourceName"];
				if ( state != null ) 
					return (string)state;
				return "";
			}
			set { ViewState["WorkingResourceName"] = value; }
		}

		[
		System.ComponentModel.DefaultValue("CommonImageTextButton")
		]
		public virtual String CssClass
		{
			get
			{
				Object state = ViewState["CssClass"];
				if ( state != null ) 
				{
					return (String)state;
				}
				return "CommonImageTextButton";
			}
			set
			{
				ViewState["CssClass"] = value;
			}
		}

		#endregion

		#region Control Wiring

		protected override void OnLoad(EventArgs e)
		{
			AjaxManager.Register(this, "GroupSubscribeLinkButton", true, AjaxDebug.None);
			base.OnLoad (e);
		}


		protected override void CreateChildControls()
		{
			CSContext csContext = CSContext.Current;
			User user = csContext.User;

			if (user.IsAnonymous || csContext.QueryString["personalize"] != "true")
				return;

			foreach(int i in user.GroupIgnoreFilter)
			{
				if(i == group.GroupID)
				{
					this.InnerText = ResourceManager.GetString(TrackingResourceName);
					break;
				}
			}
            
			if(Globals.IsNullorEmpty(this.InnerText))
				this.InnerText = ResourceManager.GetString(NotTrackingResourceName);
	

		this.HRef = string.Format("javascript:ToggleGroup({0},'{1}');",group.GroupID,this.ClientID);
	}

		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if(CSContext.Current.User.IsAnonymous)
				return;
			
	
				BuildCallbackScript();
		}

		private void BuildCallbackScript()
		{
			StringBuilder sb = new StringBuilder();
			string uniqueID = UniqueID.Replace(":", "_");

			sb.Append("<script language='javascript' type=\"text/javascript\">\n");

			sb.Append("function ToggleGroup(groupID, groupLinkControl)\n{\n");
	
			sb.Append("var control =  document.getElementById(groupLinkControl);\n");
			sb.Append("var text = control.innerHTML;\n");
			if(WorkingResourceName != string.Empty)
				sb.AppendFormat("control.innerHTML = '{0}';\n",ResourceManager.GetString(WorkingResourceName).Replace("'", "\'"));

			sb.Append("GroupSubscribeLinkButton.ToggleGroupFilter(groupLinkControl,groupID,text,groupLinkControl,ToggleGroupCallback);\n");
	
			sb.Append("}\n");

			sb.Append("function ToggleGroupCallback(response)\n{\n");
	
	
		sb.Append("if(response.error == null)\n");
		sb.Append("{\n");
		sb.Append("var control =  document.getElementById(response.value[1]);\n");
		sb.Append("control.innerHTML = response.value[0];\n");
		sb.Append("}\n");
		sb.Append("else\n");
		sb.Append("{\n");
		sb.Append("alert(response.error);");
		sb.Append("}\n");
		sb.Append("}\n");
		
	
	
			sb.Append("</script>");

			Page.RegisterClientScriptBlock("GroupSubscribeCallback", sb.ToString());
		}


		#endregion

		#region Event Handlers/Callbacks

		[AjaxMethod(IncludeControlValuesWithCallBack=false)]
		public string[] ToggleGroupFilter(int groupID, string currentText, string id)
		{
			string[] sa = new string[2];
			sa[0] = "Error";
			sa[1] = id;
			try
			{
				
				User user = CSContext.Current.User;
				if(!user.IsAnonymous)
				{
					if(currentText == ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'"))
					{
						user.AddGroupFilter(groupID);
						sa[0] = ResourceManager.GetString(TrackingResourceName).Replace("'", "\'");
					}
					else
					{
						user.RemoveGroupFilter(groupID);
						sa[0] = ResourceManager.GetString(NotTrackingResourceName).Replace("'", "\'");
					}
					Users.UpdateUser(user);
				}
				//CSContext.Current.User.SectionIgnoreFilter = new int[] {sectionID};
				
			}
			catch(Exception e)
			{
				new CSException(CSExceptionType.UnknownError, "Error in ThreadSubscribeLinkButton callback", e).Log();
				
			}

			//return returnValue;
			return sa;
		}

		#endregion

	}
}
